package com.example.mingyue.task.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.mingyue.constant.MqConstant;
import com.example.mingyue.model.entity.Post;
import com.example.mingyue.service.PostService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 初始化springboot获取帖子列表
 */
@Component
@Order(1)
@Slf4j
public class initializationPostList implements CommandLineRunner {

    @Resource
    private PostService postService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public void run(String... args) throws Exception {
        /**
         * 1.获取数据
         */
        //请求的地址
        String url = "https://api.codefather.cn/api/recommend/list/page/vo";
        //请求的参数
        String json = "{\"reviewStatus\":1,\"needNotInterests\":true,\"hiddenContent\":true,\"needCursor\":true,\"needFilterVipContent\":true,\"needOnlyRecommend\":true,\"cursorList\":[{\"field\":\"recommendTime\",\"asc\":false},{\"field\":\"id\",\"asc\":false}],\"queryType\":\"recommend\"}";
        String result = HttpRequest.post(url)
                .body(json)
                .execute().body();
        /**
         * 2.数据清洗:json转对象
         */
        Map<String,Object> map = JSONUtil.toBean(result, Map.class);
        JSONObject data = (JSONObject) map.get("data");
        JSONArray records = (JSONArray)data.get("records");
        List<Post> postList = new ArrayList<>();
        for (Object record : records) {
            JSONObject recordNew = (JSONObject) record;
            Post post = new Post();

            JSONArray tags = (JSONArray) recordNew.get("tags");
            List<String> list = tags.toList(String.class);
            post.setTags(JSONUtil.toJsonStr(list));

            post.setContent(recordNew.getStr("content"));
            post.setThumbNum(0);
            post.setFavourNum(0);
            post.setUserId(0L);
            post.setCreateTime(new Date());
            post.setUpdateTime(new Date());
            postList.add(post);
        }
        /**
         * 3.离线爬取数据存储到数据库
         */
        boolean b = postService.saveBatch(postList);
        for (Post post : postList) {
            System.out.println(post.getId());
            rabbitTemplate.convertAndSend(MqConstant.MINGYUE_EXCHANGE,MqConstant.MINGYUE_INSERTPOST_KEY,post.getId());
        }



        if(b){
            log.info("初始化帖子成功，条数={}",postList.size());
        }else{
            log.error("初始化帖子失败，条数={}",postList.size());
        }
    }

}
